package org.bp.ioc.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bp.ioc.bean.Data;
import org.bp.ioc.bean.Handler;
import org.bp.ioc.bean.Param;
import org.bp.ioc.bean.View;
import org.bp.ioc.config.BeanHelper;
import org.bp.ioc.config.ConfigHelper;
import org.bp.ioc.config.ControllerHelper;
import org.bp.ioc.config.LoadHelper;
import org.bp.ioc.utils.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@WebServlet(urlPatterns = "/*",loadOnStartup = 0)
public class DispatchServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        //help 初始化
        LoadHelper.init();
        //注册相关的servlet
        ServletContext context = config.getServletContext();
        //处理jsp的Servlet
        ServletRegistration jspServlet = context.getServletRegistration("jsp");
        jspServlet.addMapping(ConfigHelper.getWEB_JSP_PATH() + "*");
        //默认的处理静态资源的Servlet
        ServletRegistration defaultServlet = context.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getWEB_ASSET_PATH() + "*");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestMethod = req.getMethod().toLowerCase();
        String requestPath = req.getPathInfo();
        Handler handler = ControllerHelper.getHander(requestMethod,requestPath);
        if(ObjectUtils.isNotNull(handler)){
            //获取实例
            Object controller = BeanHelper.getBean(handler.getControllerClass());
            //获取参数
            Map<String,Object> paramMap = new HashMap<>();
            Enumeration<String> parameterNames = req.getParameterNames();
            while (parameterNames.hasMoreElements()){
                String name = parameterNames.nextElement();
                paramMap.put(name,req.getParameter(name));
            }
            //body内容
            String body = CodecUtils.decoderURL(StreamUtils.getStrFromInputStream(req.getInputStream()));
            if(ObjectUtils.isNotNull(body)){
                String[] params = StringUtils.splitString(body, "&");
                if(ObjectUtils.isNotNull(params)){
                    for (String param : params){
                        String[] arr = StringUtils.splitString(param, "=");
                        if(ObjectUtils.isNotNull(arr) && arr.length==2){
                            paramMap.put(arr[0],arr[1]);
                        }
                    }
                }
            }
            //执行Action方法
            Param param = new Param(paramMap);
            Method actionMethod = handler.getActionMethod();
            Object result = ReflectionUtils.invokeMethod(controller, actionMethod, param);
            //处理Action返回值
            if(result instanceof View){
                //转发为jsp
                View view = (View) result;
                String path = view.getPath();
                if(ObjectUtils.isNotNull(path)){
                    if(path.startsWith("/")){//重定向
                        resp.sendRedirect(req.getContextPath() + path);
                    }else { //转发
                        Map<String, Object> model = view.getModel();
                        if(ObjectUtils.isNotNull(model)){
                            Set<Map.Entry<String, Object>> entries = model.entrySet();
                            for (Map.Entry<String, Object> entry :entries){
                                req.setAttribute(entry.getKey(),entry.getValue());
                            }
                        }
                        req.getRequestDispatcher(ConfigHelper.getWEB_JSP_PATH() + path).forward(req,resp);
                    }
                }
            }else if(result instanceof Data){
                //请求json数据
                Data data = (Data) result;
                Object model = data.getModel();
                if(ObjectUtils.isNotNull(model)) {
                    String json = JsonUtils.objectToJson(model);
                    resp.setContentType("application/json");
                    resp.setCharacterEncoding("UTF-8");
                    PrintWriter writer = resp.getWriter();
                    writer.print(json);
                    StreamUtils.close(writer);
                }
            }
        }
    }
}
